package com.ihighest.app.infox.activity;

import java.util.ArrayList;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.DragAdapter;
import com.ihighest.app.infox.adapter.OtherAdapter;
import com.ihighest.app.infox.bean.ChannelItem;
import com.ihighest.app.infox.bean.ChannelManage;
import com.ihighest.app.infox.myview.DragGrid;
import com.ihighest.app.infox.myview.OtherGridView;

/**
 * 频道管理
 */
public class ChannelActivity extends BaseActivity {
	public static String TAG = "ChannelActivity";
	/** 用户栏目的GRIDVIEW */
	private DragGrid userGridView;
	/** 其它栏目的GRIDVIEW */
	private OtherGridView otherGridView;
	/** 用户栏目对应的适配器，可以拖动 */
	DragAdapter userAdapter;
	/** 其它栏目对应的适配器 */
	OtherAdapter otherAdapter;
	/** 其它栏目列表 */
	ArrayList<ChannelItem> otherChannelList = new ArrayList<ChannelItem>();
	/** 用户栏目列表 */
	ArrayList<ChannelItem> userChannelList = new ArrayList<ChannelItem>();
	/** 是否在移动，由于这边是动画结束后才进行的数据更替，设置这个限制为了避免操作太频繁造成的数据错乱。 */
	boolean isMove = false;
	private TextView editChannel;
	private ImageView closeChannel;
	
	public static boolean  isEdit=false; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_channel);
		initView();
		initData();
	}

	/** 初始化数据 */
	private void initData() {

		userChannelList = ((ArrayList<ChannelItem>) ChannelManage.getManage(Application.getInstance().getSQLHelper()).getUserChannel());
		otherChannelList = ((ArrayList<ChannelItem>) ChannelManage.getManage(Application.getInstance().getSQLHelper()).getOtherChannel());
		userAdapter = new DragAdapter(this, userChannelList);
		userGridView.setAdapter(userAdapter);
		otherAdapter = new OtherAdapter(this, otherChannelList);
		otherGridView.setAdapter(otherAdapter);

	}

	/** 初始化布局 */
	private void initView() {
		editChannel = (TextView) findViewById(R.id.channelEdit);
		closeChannel = (ImageView) findViewById(R.id.channelClose);
		userGridView = (DragGrid) findViewById(R.id.userGridView);

		otherGridView = (OtherGridView) findViewById(R.id.otherGridView);
		userGridView.setClickable(false);
		otherGridView.setClickable(false);
		closeChannel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		editChannel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (editChannel.getText().toString().equals("完成")) {
					saveChannel();
					if (userAdapter.isListChanged()) {
						dataChange();
					} else {

					}
					overridePendingTransition(R.anim.infox_slide_in_left, R.anim.infox_slide_out_right);
					isEdit=false;
					finish();
				} else {
					// 设置GRIDVIEW的ITEM的点击监听
					otherGridView.setOnItemClickListener(new Mylistener());
					userGridView.setOnItemClickListener(new Mylistener());
					editChannel.setText("完成");
					isEdit=true;

				}

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * 点击ITEM移动动画
	 * 
	 * @param moveView
	 * @param startLocation
	 * @param endLocation
	 * @param moveChannel
	 * @param clickGridView
	 */
	private void MoveAnim(View moveView, int[] startLocation, int[] endLocation, final ChannelItem moveChannel, final GridView clickGridView) {
		int[] initLocation = new int[2];
		// 获取传递过来的VIEW的坐标
		moveView.getLocationInWindow(initLocation);
		// 得到要移动的VIEW,并放入对应的容器中
		final ViewGroup moveViewGroup = getMoveViewGroup();
		final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
		// 创建移动动画
		TranslateAnimation moveAnimation = new TranslateAnimation(startLocation[0], endLocation[0], startLocation[1], endLocation[1]);
		moveAnimation.setDuration(300L);// 动画时间
		// 动画配置
		AnimationSet moveAnimationSet = new AnimationSet(true);
		moveAnimationSet.setFillAfter(false);// 动画效果执行完毕后，View对象不保留在终止的位置
		moveAnimationSet.addAnimation(moveAnimation);
		mMoveView.startAnimation(moveAnimationSet);
		moveAnimationSet.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				isMove = true;
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				moveViewGroup.removeView(mMoveView);
				// instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
				if (clickGridView instanceof DragGrid) {
					otherAdapter.setVisible(true);
					otherAdapter.notifyDataSetChanged();
					userAdapter.remove();
				} else {
					userAdapter.setVisible(true);
					userAdapter.notifyDataSetChanged();
					otherAdapter.remove();
				}
				isMove = false;
			}
		});
	}

	/**
	 * 获取移动的VIEW，放入对应ViewGroup布局容器
	 * 
	 * @param viewGroup
	 * @param view
	 * @param initLocation
	 * @return
	 */
	private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
		int x = initLocation[0];
		int y = initLocation[1];
		viewGroup.addView(view);
		LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mLayoutParams.leftMargin = x;
		mLayoutParams.topMargin = y;
		view.setLayoutParams(mLayoutParams);
		return view;
	}

	/**
	 * 创建移动的ITEM对应的ViewGroup布局容器
	 */
	private ViewGroup getMoveViewGroup() {
		ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
		LinearLayout moveLinearLayout = new LinearLayout(this);
		moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		moveViewGroup.addView(moveLinearLayout);
		return moveLinearLayout;
	}

	/**
	 * 获取点击的Item的对应View，
	 * 
	 * @param view
	 * @return
	 */
	private ImageView getView(View view) {
		view.destroyDrawingCache();
		view.setDrawingCacheEnabled(true);
		Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
		view.setDrawingCacheEnabled(false);
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(cache);
		return iv;
	}

	/** 退出时候保存选择后数据库的设置 */
	private void saveChannel() {
		ChannelManage.deleteAllChannel();
		ChannelManage.getManage(Application.getInstance().getSQLHelper()).saveUserChannel(userAdapter.getChannnelLst());
		ChannelManage.getManage(Application.getInstance().getSQLHelper()).saveOtherChannel(otherAdapter.getChannnelLst());
		String string="";
		for (int i = 0; i < userAdapter.getChannnelLst().size(); i++) {
			System.out.println("频道顺序" + userAdapter.getChannnelLst().get(i).getName());
			string=string+userAdapter.getChannnelLst().get(i).getId()+"_"+i+",";
		}
		//频道顺序提交服务器
		subchannenl(string );
		
	}
	

	private void subchannenl(String string) {
		// TODO Auto-generated method stub
		Api.post("me/subscribeChannels", ApiParam.create().addParam("id_index", string), new ApiCallback(this) {
			
			@Override
			public void handleSuccess(ApiResult result) {
				// TODO Auto-generated method stub
				if(result.getCode()==100){
					System.out.println("频道数据提交成功");
				}
			}
			
			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub
				
			}
		},this);
				
	}

	@Override
	public void onBackPressed() {
		saveChannel();
		if (userAdapter.isListChanged()) {
			dataChange();
		} else {
			super.onBackPressed();
		}
		overridePendingTransition(R.anim.infox_slide_in_left, R.anim.infox_slide_out_right);
	}

	/**
	 * 数据发生变化
	 * 
	 * 
	 * @author lkx Created at 2015-10-16 下午2:17:29
	 */
	private void dataChange() {
		Intent mIntent = new Intent(Const.DATACHANGE);
		// 发送广播
		sendBroadcast(mIntent);
		finish();
		Log.d(TAG, "数据发生改变");

	}

	class Mylistener implements OnItemClickListener {

		/** GRIDVIEW对应的ITEM点击监听接口 */
		@Override
		public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
			// 如果点击的时候，之前动画还没结束，那么就让点击事件无效
			if (isMove) {
				return;
			}
			switch (parent.getId()) {
			case R.id.userGridView:
				// position为 0，1 的不可以进行任何操作

				final ChannelItem channeluser = ((DragAdapter) parent.getAdapter()).getItem(position);// 获取点击的频道内容

				// if (position != 0 && position != 1) {
				if (!channeluser.getCancel().equals("false")) {
					final ImageView moveImageView = getView(view);
					if (moveImageView != null) {
						TextView newTextView = (TextView) view.findViewById(R.id.text_item);
						final int[] startLocation = new int[2];
						newTextView.getLocationInWindow(startLocation);
						// final ChannelItem channel = ((DragAdapter)
						// parent.getAdapter()).getItem(position);// 获取点击的频道内容
						otherAdapter.setVisible(false);
						// 绑定频道提交数据
						submitChannel(channeluser.getId(), "2");

						// 添加到最后一个

						otherAdapter.addItem(channeluser);
						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								try {
									int[] endLocation = new int[2];
									// 获取终点的坐标
									otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
									MoveAnim(moveImageView, startLocation, endLocation, channeluser, userGridView);
									userAdapter.setRemove(position);
								} catch (Exception localException) {
								}
							}
						}, 50L);
					}
				}
				break;
			case R.id.otherGridView:
				final ImageView moveImageView = getView(view);
				if (moveImageView != null) {
					TextView newTextView = (TextView) view.findViewById(R.id.text_item);
					final int[] startLocation = new int[2];
					newTextView.getLocationInWindow(startLocation);
					final ChannelItem channel = ((OtherAdapter) parent.getAdapter()).getItem(position);
					userAdapter.setVisible(false);

					submitChannel(channel.getId(), "1");
					// 添加到最后一个
					userAdapter.addItem(channel);
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							try {
								int[] endLocation = new int[2];
								// 获取终点的坐标
								userGridView.getChildAt(userGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
								MoveAnim(moveImageView, startLocation, endLocation, channel, otherGridView);
								otherAdapter.setRemove(position);
							} catch (Exception localException) {
							}
						}
					}, 50L);
				}
				break;
			default:
				break;
			}
		}

		/**
		 * 
		 * 绑定（解除）频道提交数据
		 * 
		 * 
		 * @author yyh Created at 2015-10-22 下午2:35:32
		 */

		private void submitChannel(String id, String type) {
			Api.post("me/followChannel", ApiParam.create().addParam("id", id).addParam("type", type), new ApiCallback(ChannelActivity.this,
					true) {

				@Override
				public void handleSuccess(ApiResult result) {
					Log.e("channel", "绑定");
				}

				@Override
				public void handleFailure(Exception e, String msg) {
					Log.e("channel", "绑定失败");
				}
			}, ChannelActivity.this);

		}

	}
}
